package com.turing.data.scripts.xgpsgg.filter

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.turing.common.util.FileUtils
import com.turing.common.util.Log
import com.turing.common.util.StringUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO
import org.apache.poi.util.StringUtil

class InvestorName_12349_r15_rule {

    public static void main(String[] args) {
        DependParamsVO param = new DependParamsVO()
        param.setJSONPathMap(new LinkedHashMap<String, String>())
//        param.getJSONPathMap().put("abc", "http://media.tlrobot.com/group1/M00/0C/29/rBIHD2CjdRiAPV_eAACdNH_q44831.json")
//        param.getJSONPathMap().put("abc", "/Users/luoshiwei/Desktop/tmp/ex/extractor/e675314b-1c3b-4bb7-9a9f-ef5c268b7b6d/688316_20210305_1/json/688316_20210305_1_converted.json")
        param.getJSONPathMap().put("abc", "D:\\111.json")
        List<TaskElementVO.DrawResultVO> s = doConvert(param)
        for (int z = 0; z < s.size(); z++) {
            def get = s.get(z)
//            println(get.text)
        }
    }

    static List<TaskElementVO.DrawResultVO> doConvert(DependParamsVO dependParams) {
//        Log.info(">>>>>>>>>>>>JSONPathMap"+dependParams.JSONPathMap)
//        Log.info(">>>>>>>>>>>>textPathMap"+dependParams.textPathMap)
//        def REGEX_COMPANY_1 = /.*银华.*/
//        def REGEX_COMPANY_1 = /.*/
        String SEARCH_TITLE = "投资者名称"

        String[] Search_Titles = ["投资者名称","机构名称","投资者","网下投资者名称"]
        Date begin = new Date()
        Date end = new Date()

        List<String> titleList = new LinkedList<>()
        Map<String, String> oldAndNewTitleMap = new HashMap<>()
        Map<String, String> titleAndValueMap = new HashMap<>()
//        Map<String, List<String>> DictionArtesMap = dependParams.getDictionArtes();
//        List<String> dictionArtes = DictionArtesMap.get("证券账户")

        List<String> keys = dependParams.getJSONPathMap().keySet() as List<String>
        List<TaskElementVO.DrawResultVO> finalResults = new ArrayList<>()

        for (int z = 0; z < keys.size(); z++) {
            String path = dependParams.getJSONPathMap().get(keys.get(z))
            String format_json_path = "/Users/luoshiwei/Desktop/response.json"

            if (!StringUtils.isEmpty(path)) {
                format_json_path = path
            }

            begin = new Date()
            String jsonString = FileUtils.loadJson(format_json_path)

//            Log.info(">>>>>>>>>>>>jsonString"+jsonString)


            List<String> newTitleList = ["序号", "投资者名称", "配售对象名称", "证券账户", "申购数量（万股）",
                                         "初步配售数量（股）", "获配金额（元）",
                                         "经纪佣金（元）", "合计应缴（元）", "分类"]
            List<String> oldTitleList = ["序号", "投资者名称", "配售对象名称", "证券账户", "申购数量（万股）",
                                         "初步配售数量（股）", "获配金额（元）",
                                         "经纪佣金（元）", "合计应缴（元）", "分类"]
            end = new Date()
            println "load json: " + (end.getTime() - begin.getTime()) / 1000 / 1000


            //标题映射
            for (int i = 0; i < newTitleList.size(); i++) {
                String newTitle = newTitleList[i]
                String oldTitle = oldTitleList[i]
                oldAndNewTitleMap.put(oldTitle, newTitle)
            }


            boolean foundTitle = false

            begin = new Date()
            JSONArray formatArr = JSONArray.parse(jsonString)
            end = new Date()
            println "parse json array: " + (end.getTime() - begin.getTime()) / 1000 / 1000

            begin = new Date()
            println begin

            try{
                for (int pageNo = 0; pageNo < formatArr.size(); pageNo++) {

                    JSONObject pageObj = formatArr.getJSONObject(pageNo)
                    JSONArray paraArr = pageObj.getJSONArray("paragraphs")

//                    JSONObject pageObj2 = formatArr.getJSONObject(pageNo + 1)
//                    JSONArray paraArr2 = pageObj2.getJSONArray("paragraphs")


                    for (int paragraphsNo = 0; paragraphsNo < paraArr.size(); paragraphsNo++) {
//                        if(paragraphsNo>1){
//                            JSONObject paraObj2 = paraArr2.getJSONObject(paragraphsNo - 1)
//                            JSONArray lineArr2 = paraObj2.getJSONArray("lines")
//                            JSONObject lineObj2 = lineArr2.getJSONObject(1)
//                            String objString = lineObj2.getString("objContent")
//                            Log.info(">>>>>>>>>>objString"+objString)
//                        }


                        JSONObject paraObj = paraArr.getJSONObject(paragraphsNo)
                        JSONArray lineArr = paraObj.getJSONArray("lines")
                        //每一行
                        for (int line = 0; line < lineArr.size(); line++) {
                            titleAndValueMap = new HashMap<>()
                            JSONObject lineObj = lineArr.getJSONObject(line)

                            String lineId = lineObj.getString("lineId")
                            if (JSON.isValidArray(lineObj.getString("cells"))) {
                                JSONArray objContentArr = lineObj.getJSONArray("cells")
                                if (!StringUtils.isEmpty(objContentArr) && objContentArr.size()>6) {

                                    if (!foundTitle) {
                                        int foundTitleNum = 0
                                        //找表头
                                        for (int i = 0; i < objContentArr.size(); i++) {
                                            JSONObject objContentObj = objContentArr.getJSONObject(i)
                                            String objContentString = objContentObj.getString("objContent")
                                            if (objContentString.contains("\r")) {
                                                objContentString = objContentString.replace("\r", "")
                                            }

                                            String title = oldAndNewTitleMap.get(objContentString)

//                                            if(title != null &&objContentArr.size()<=6 && Search_Titles.contains(title)){
//                                                continue
//                                            }

                                            //标题栏
                                            if (oldTitleList.contains(objContentString)
                                                    || newTitleList.contains(objContentString)
                                                    || arrContains(Search_Titles, objContentString)) {
                                                foundTitleNum++

                                            }



//                                                if(title.contains("投资者名称")){
//                                                    Log.info(">>>>>>>>>>>>>>定位到的长度"+objContentArr.size())
//
//                                                }
//                                            Log.info(">>>>>>>>>>>>>>定位到的标题={}"+title)
                                            if (!StringUtils.isEmpty(title)) {
                                                titleList.add(title)
                                            } else if (arrContains(Search_Titles, objContentString)) {
                                                titleList.add(SEARCH_TITLE)
                                            } else {
                                                titleList.add(objContentString)
                                            }

                                        }
                                        if (foundTitleNum >= 3) {
                                            foundTitle = true
                                        } else {
                                            titleList = new LinkedList<>()
                                        }

                                    } else {
                                        def wordCount = 0
                                        //每一列
                                        for (int column = 0; column < objContentArr.size(); column++) {
                                            JSONObject objContentObj = objContentArr.getJSONObject(column)
                                            String objContentString = objContentObj.getString("objContent")
                                            String values = ""


                                            // && line == lineArr.size() - 2

                                            if(pageNo + 1 < formatArr.size() && line == lineArr.size() - 2){
                                                JSONObject pageObj2 = formatArr.getJSONObject(pageNo + 1)
                                                JSONArray paraArr2 = pageObj2.getJSONArray("paragraphs")
                                                JSONObject paraObj2 = paraArr2.getJSONObject(paragraphsNo)
                                                JSONArray lineArr2 = paraObj2.getJSONArray("lines")
                                                JSONObject lineObj2 = lineArr2.getJSONObject(1)
                                                String objString = lineObj2.getString("objContent")
                                                if(objString.contains("::::")){
                                                    String[] objStrings = objString.split(":")
                                                    values = objStrings[1]
//                                                        println(">>>>>>>>>>line" + line)
//                                                        println(">>>>>>>>>>lineArr" +  lineArr.size())
//                                                        println(">>>>>>>>>>lineArr-2={}" +  lineArr.size()-2)
                                                }
                                            }
//                                                }
                                            def cWordCount = objContentString.length()
                                            if (objContentString.contains("\r")) {
                                                objContentString = objContentString.replace("\r", "")
                                            }
                                            //具体数值栏
                                            if (foundTitle) {
                                                String title = titleList[column]
                                                if (title != null && !StringUtils.isEmpty(title)) {
                                                    titleAndValueMap.put(title, objContentString)
                                                }
                                                String businessValue = titleAndValueMap.get(SEARCH_TITLE)
//                                                    Log.info(">>>>>>>>>>>>>>>>>businessValue为"+businessValue)
                                                if (!StringUtils.isEmpty(businessValue) && (title != null &&
                                                        (title.contains(SEARCH_TITLE) || Search_Titles.contains(title)))) {
                                                    TaskElementVO.DrawResultVO drawResultVO = new TaskElementVO.DrawResultVO()
                                                    objContentString = objContentString.replace(",", "")
                                                    if(!StringUtils.isEmpty(values)){
                                                        objContentString = objContentString + values
                                                    }
                                                    drawResultVO.setBusinessValue(objContentString)

                                                    drawResultVO.setText(objContentString)
                                                    drawResultVO.setPara_info([lineId])
                                                    drawResultVO.setPos_info([wordCount, cWordCount + wordCount])
                                                    drawResultVO.setPage(lineId.split("_")[1] as Integer)
                                                    drawResultVO.setChildTaskSn(keys.get(z))
                                                    drawResultVO.setType(1)
                                                    if(!Search_Titles.contains(objContentString)){
                                                        finalResults.add(drawResultVO)
                                                        println(drawResultVO.businessValue)

                                                    }
                                                }
                                            }
                                            wordCount += cWordCount
                                        }
//                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }catch(Exception e){
                Log.error(">>>>>>>>>>>>>>>e"+e)
                e.printStackTrace()
            }


//            }


            end = new Date()
            println end
            println "ex elements: " + (end.getTime() - begin.getTime()) / 1000 / 1000
        }


        Log.info(">>>>>>>>>>>>>>>>>投资者名称的结果对象有"+finalResults.size()+"个")

        if(finalResults.size()==0){
            TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
            defaultDrawResultVO.text = ""
            finalResults.add(defaultDrawResultVO)
        }


        return finalResults
    }

    static boolean arrContains(String[] Search_Titles, String objContentString) {
        if (Search_Titles.contains(objContentString)) {
            return true
        }
        for (i in 0..<Search_Titles.length) {
            String title = Search_Titles[i]
            title = title.replaceAll(" ", "")
                    .replaceAll("（", "(")
                    .replaceAll("）", ")")
                    .replaceAll("万", "")
            String anoContentString = objContentString.replaceAll(" ", "")
                    .replaceAll("（", "(")
                    .replaceAll("）", ")")
                    .replaceAll("万", "")
            if (title == anoContentString) {
                return true
            }

        }

        return false
    }
}
